package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDAO;
import model.User;
import model.UserDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-07
 * Time:17:29
 */
@WebServlet("/authorInfo")
public class AuthorServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 获取指定博客的作者信息
        String param = req.getParameter("blogId");
        if (param == null || "".equals(param)) {
            // 参数缺少
            resp.getWriter().write("{\"ok\":false,\"reason\":\"参数缺失！\"}");
            return;
        }

        // 根据当前的blogId在数据库中找到对应的blog对象，再进一步找到作者信息
        BlogDAO blogDAO =  new BlogDAO();
        Blog blog = blogDAO.selectOne(Integer.parseInt(param));
        if (blog == null) {
            resp.getWriter().write("{\"ok\":false,\"reason\":\"博客不存在！\"}");
        }

        // 根据blog对象查询用户对象
        UserDAO userDAO = new UserDAO();
        User author = userDAO.selectById(blog.getUserId());
        if (author == null) {
            resp.getWriter().write("{\"ok\":false,\"reason\":\"用户不存在！\"}");
        }

        // 把author返回到浏览器端
        author.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(author));
    }
}
